package com.shop.om.conf;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

@Configuration
@MapperScan(basePackages = "com.shop.om.*.mapper",sqlSessionFactoryRef = "sqlSessionFactory1")
public class mybatisConfig {
	
	@Resource
	@Qualifier("dataSource1")
	private DataSource dataSource1;
	
	@Value("${mybatis.mapperLocations}")
	private String mapperLocations; 
	
	@Bean(name = "sqlSessionFactory1")
	public SqlSessionFactory sqlSessionFactory1() throws Exception{	
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		bean.setDataSource(dataSource1);
		bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocations));
		org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
		//下划线转大写
		configuration.setMapUnderscoreToCamelCase(true);
		bean.setConfiguration(configuration);
		return  bean.getObject();
	}
	//配置事务管理器
    @Bean(name = "TransactionManager1")
    public DataSourceTransactionManager testTransactionManager(@Qualifier("dataSource1") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "SqlSessionTemplate")
    public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("sqlSessionFactory1") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

	
	
}
